package pers.twm.mybatis.provider.filter;

import com.intellij.execution.filters.Filter;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.JBColor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import pers.twm.mybatis.ui.LogExecutor;

import java.awt.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import static pers.twm.mybatis.util.SqlUtil.populateSql;

/**
 * @ClassName SqlLogConsoleFilter
 * @Description TODO
 * @Author tianwanming
 * @Date 2023/2/26 21:24
 * @Version 1.0
 */
public class MyBatisSqlLogConsoleFilter  implements Filter {

    private final Project project;

    private String sqlLine = null;

    private String sqlParameter = null;

    private String logPrefix = null;

    private final String preparing = "Preparing: ";
    private final String parameters = "Parameters: ";

    private AtomicInteger cumsum = new AtomicInteger(1);

    public MyBatisSqlLogConsoleFilter(Project project) {
        this.project = project;
    }

    @Override
    public @Nullable Result applyFilter(@NotNull String lineVal, int i) {

        LogExecutor userData = project.getUserData(LogExecutor.KEY);

        if(Objects.isNull(userData)) {
            return null;
        }
        if(StringUtil.isEmpty(lineVal)) {
            return null;
        }
        if(lineVal.contains(preparing)) {
            int indexOf = lineVal.indexOf(preparing);
            this.sqlLine = lineVal.substring(indexOf+preparing.length());
            return null;
        }

        if(StringUtil.isEmpty(sqlLine) || !lineVal.contains(parameters)) {
            return null;
        }
        int index = lineVal.indexOf(parameters);
        this.sqlParameter = lineVal.substring(index+parameters.length());

        String sql = populateSql(sqlLine, sqlParameter);
        print(userData,sql);

        this.sqlLine = null;
        this.sqlParameter = null;
        this.logPrefix = null;
        return null;
    }


    private void print(LogExecutor userData,String sql) {

        int andGet = cumsum.addAndGet(1);
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss E"));
        userData.printSql(sql,andGet,date);
    }

}
